<?php

namespace app\home\controller;

use app\home\model\Idfa724Model;
use app\home\model\Order;
use app\home\service\NotifyService;
use app\home\service\OrderService;
use think\Db;
use think\helper\hash\Md5;
use think\Model;
use think\Request;
use think\response\Json;

class Pay800068 extends BasePay{

    const  key = 'MJFQTTFZP0ZLVHLJHLWWNRZI2YXWVO6EAPIBUG4OE9ZYHOZOBXUSIXIM9ZB0CQVQ8SNE4OKXVC8YO5CRW4PVGBWEBRHQZVGKDK0BWINW7CYAXDQFVNQT4HPEWJDSOD7R';


    public function __construct()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 
    }

    public function order()
    {
        parent::order();
        $params = Request::instance()->param();



        $json_string = file_get_contents(env('PLATFORM.USD'));

        $config = json_decode($json_string, true);
        $usd  = $config[$this->order_array['goods_id']];
        if(empty($usd)){
            mylog('计费点对应的美元金额找不到');
            return false;
        }
        //根据配置修改对应的币种 和比例
        $server_config_info = Db::connect('db_config2')->table('server_config_info')->where(['ServerName'=>'conversion'])->find();
        $data = json_decode($server_config_info['Content'],true);
        //映射国家 
        $product = [
            'thbbank'=>'泰国',
            'thbqr'=>'泰国',
        ];
        $country = $product[$params['product']];
        $res = $data[$country];
        $coin = (int)ceil($usd['Mpay'])*$res['rtion'];
        $payData = [
            'mchId'=>'724144550696', 
            "orderNo" => $this->order_array['id'],
            "amount" => $coin,
            'product'=>$params['product'],
            'bankcode'=>$params['bankcode'],
            'goods'=>'email:520155@gmail.com/name:tom/phone:7894561230/ip:8.219.187.96/payer:fdfafdfd',
            'notifyUrl'=>'https://pay.carcadefishing.com/home/pay800068/notify',
            'returnUrl'=>'https://pay.carcadefishing.com',
        ];
        $sign = md5($this->signData($payData).'&key='.self::key);
        $payData['sign'] = strtoupper($sign);

        $url = 'http://api.letspayfast.com/apipay';
        $response = $this->curl($url,$payData);
        if(empty(json_decode($response,true))){
            mylog('下单失败');
            exit(json_encode(['code'=>0,'msg'=>'','data'=>[]]));
        }
        $data = json_decode($response,true);
        if($data['retCode'] !='SUCCESS'){
            mylog('下单失败');
            exit(json_encode(['code'=>0,'msg'=>'','data'=>[]]));
        }

        (new \app\home\model\TradeLog)->where('id', $this->order_array['id'])->update(['dollPrice'=>$coin,'dollPriceType'=>$res['currency']]);

        exit(json_encode(['code'=>1,'msg'=>'','data'=>$data]));
    }

    


    public function notify()
    {
        parent::notify();
        $params = $this->params;
        mylog($params);
        try{
            //验证签名
            $str = $this->signData($params);
            $sign = md5($str.'&key='.self::key);

            if($sign != strtolower($params['sign'])){
                throw new \Exception('sign false');
            }

            if($params['status'] != 2){
                throw new \Exception('status false');
            }
            //保存第三方单号
            $tradeLog = (new \app\home\model\TradeLog)->where(['id'=>$params['orderNo']])->find();
            if ($tradeLog['dollPrice'] != $params['amount']) {
                throw new \Exception('订单金额不一致' . ' 传参:' .  $params['amount'] . ' 实际:' . $tradeLog['dollPrice']);
            }
            
            if ($tradeLog["status"] == OrderService::PAY_STATUS_PAID) {
                mylog("800068 订单已经处理过了 订单id".$tradeLog['id']);
                exit('success');
            }
            
            //发货
            $notifyService = new NotifyService();
            if($notifyService->notifyProcess($tradeLog) == false){
                throw new \Exception('notifyProcess false');
            }
            //facebook广告回传
            if(in_array($tradeLog->channel_id,(new AdFacebook())->channel_id)){
                $AdFacebook = new AdFacebook();
                $AdFacebook->pay($tradeLog->userid,$tradeLog->amount,$tradeLog->channel_id);
            }
            exit('success');
        }catch (\Exception $exception){
            mylog('800068-error:'.$exception->getMessage().' line:'.$exception->getLine().' file:'.$exception->getFile());
            exit('FAIL');
        }

    }

    public function signData($data)
    {
        ksort($data);
        $tmp = [];
        foreach ($data as $k => $v) {
            if($k == 'sign'){
                continue;
            }
            $tmp[] = $k . '=' . $v;
        }
        $str = implode('&', $tmp);
        return $str;
    }

    
    /**
     * @param $url
     * @param null $body
     * @return bool|string
     * @throws Exception
     */
    protected function curl($url, $body = null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        // curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
        curl_setopt($ch, CURLOPT_HTTPHEADER,[]);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS,  $body);
        //TODO 证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);

        curl_close($ch);
        mylog($response);
        return $response;

        
    }
   
}
